package com.bml.architect.nio;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class RoudNIOServer {
    static List<SocketChannel> channelList = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        //创建NIO ServerSocketChannel,与BIO的serverSocket类似
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        serverSocket.bind(new InetSocketAddress(8000));
        serverSocket.configureBlocking(false);
        System.out.println("服务器启动成功...");
        while (true) {
            // 非阻塞模式accept方法不会阻塞，否则会阻塞
            // NIO的非阻塞是由操作系统内部实现的，底层调用了linux内核的accept函数
            SocketChannel socketChannel = serverSocket.accept();
            if (socketChannel != null) {
                //到这里就代表有新的连接过来了，然后加入到就绪列表中
                socketChannel.configureBlocking(false);
                channelList.add(socketChannel);
            }
            // 遍历连接进行数据读取
            Iterator<SocketChannel> iterator = channelList.iterator();
            while (iterator.hasNext()) {
                SocketChannel next = iterator.next();
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                //不会阻塞
                int read = next.read(buffer);
                if (read > 0) {
                    System.out.println("接受到客户端的数据:" + new String(buffer.array(),0,read));
                } else if (read == -1) {
                    //客户端连接断开，将socket从列表移除
                    iterator.remove();
                    System.out.println("客户端断开连接");
                }
            }

        }


    }
}
